#include<iostream>
/* 两数相加 */
// Definition for singly-linked list.
  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
  };
 
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
      int sum = 0,carry=0,flag=0,a=0,b=0;
      ListNode * node = new ListNode ;
      ListNode * p = node;
      while(l1 || l2 || carry){
	if(l1){
	a = l1->val;
	}else{
	  a = 0;
	}
	if(l2){
	b = l2->val;
	}else{
	  b = 0;
	}
	sum = a + b;
	if(carry){
	  sum++; 
	}
	if(sum > 9){
	  carry = 1;
	  flag = 1;
	  node->val = sum % 10 ;
	}else{
	  carry = 0;
	  node->val = sum;
	}
	if(!flag){
	if(carry){
	  node->val++;
	}
	}else{
	  flag = 0;
	}

	if(l1){
	l1 = l1->next;
	}
	if(l2){
	l2 = l2->next;
	}
	if(l1 || l2 || carry){
	node->next = new ListNode;
	node = node->next;
	}
      }
      return p;
    }

  void fillNode(int * l, ListNode * p, int len){
    
for(int i=0;i<len; i++){
   if(i == 0){
     p->val = l[i];
   }else{
     p->next = new ListNode ;
     p = p->next;
     p->val = l[i];     
   }
    
   }
    
 
  }
};

int main(){
  // int l1[]={2,4,3}, l2[]={5,6,4};
   int l1[]={9,9,9,9,9,9,9}, l2[]={9,9,9,9};
  // int l1[]={0}, l2[]={0};
 ListNode * l1Head = new ListNode;
 ListNode * l2Head = new ListNode;
 ListNode * p = nullptr;
 Solution * s = new Solution ;
 s->fillNode(l1,l1Head,7);
 s->fillNode(l2,l2Head,4);
 p = l1Head;
 while(p){
   std::cout << p->val << std::endl;
   p = p->next;
 }
 p = l2Head;
 while(p){
   std::cout << p->val << std::endl;
   p = p->next;
 }
  
 p = s->addTwoNumbers(l1Head,l2Head);
 std::cout << std::endl;
 while(p){
  std::cout << p->val << std::endl;
  p = p->next;
 }
  return 0;
}
